import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

import '../../view/index.dart';
import '../entity/time_capsule.dart';

/// 路由路径常量
class AppRoutes {
  static const String login = '/login';
  static const String register = '/register';
  static const String main = '/main';
  static const String native = '/native';
  static const String time = '/time';
  static const String square = '/square';
  static const String my = '/my';
  static const String home = '/home';
  static const String shareDetail = '/share_detail';
  static const String setting = '/setting';
  static const String timeCapsule = '/time_capsule';
  static const String emailInput = '/email_input';
  static const String timeCapsuleSent = '/time_capsule_sent';
  static const String timeCapsuleDetail = '/time_capsule_detail';
  static const String userInfo = '/user_info';
  static const String messageList = '/message_list';
  static const String chat = '/chat';
  static const String subscribe = '/subscribe';
}

/// 全局路由配置
class AppRouter {
  static final GoRouter _router = GoRouter(
    initialLocation: AppRoutes.native,
    routes: [
      // 登录页面
      GoRoute(
        path: AppRoutes.login,
        name: 'login',
        pageBuilder: (context, state) =>
            _buildPageWithAnimation(context, state, LoginPage()),
      ),

      // 注册页面
      GoRoute(
        path: AppRoutes.register,
        name: 'register',
        pageBuilder: (context, state) =>
            _buildPageWithAnimation(context, state, const RegisterPage()),
      ),

      // 主页面
      GoRoute(
        path: AppRoutes.main,
        name: 'main',
        pageBuilder: (context, state) => _buildPageWithConditionalAnimation(
          context,
          state,
          const MainPage(),
        ),
      ),

      // 原生页面
      GoRoute(
        path: AppRoutes.native,
        name: 'native',
        pageBuilder: (context, state) =>
            _buildPageWithAnimation(context, state, const NativePage()),
      ),

      // 首页重定向到登录页
      GoRoute(
        path: AppRoutes.home,
        name: 'home',
        pageBuilder: (context, state) =>
            _buildPageWithAnimation(context, state, const HomePage()),
      ),

      // 时间页面
      GoRoute(
        path: AppRoutes.time,
        name: 'time',
        pageBuilder: (context, state) =>
            _buildPageWithAnimation(context, state, const TimePage()),
      ),

      // 广场页面
      GoRoute(
        path: AppRoutes.square,
        name: 'square',
        pageBuilder: (context, state) =>
            _buildPageWithAnimation(context, state, const SquarePage()),
      ),

      // 我的页面
      GoRoute(
        path: AppRoutes.my,
        name: 'my',
        pageBuilder: (context, state) =>
            _buildPageWithAnimation(context, state, MyPage()),
      ),

      // 分享详情页面
      GoRoute(
        path: AppRoutes.shareDetail,
        name: 'share_detail',
        pageBuilder: (context, state) =>
            _buildPageWithAnimation(context, state, const ShareDetailPage()),
      ),

      // 设置页面
      GoRoute(
        path: AppRoutes.setting,
        name: 'setting',
        pageBuilder: (context, state) =>
            _buildPageWithAnimation(context, state, const SettingPage()),
      ),

      // 时间胶囊页面
      GoRoute(
        path: AppRoutes.timeCapsule,
        name: 'time_capsule',
        pageBuilder: (context, state) =>
            _buildPageWithAnimation(context, state, const TimeCapsulePage()),
      ),

      // 邮箱输入页面
      GoRoute(
        path: AppRoutes.emailInput,
        name: 'email_input',
        pageBuilder: (context, state) {
          final timeCapsule = state.extra as TimeCapsule;
          return _buildPageWithAnimation(
            context,
            state,
            EmailInputPage(timeCapsule: timeCapsule),
          );
        },
      ),

      // 时间胶囊发送页面
      GoRoute(
        path: AppRoutes.timeCapsuleSent,
        name: 'time_capsule_sent',
        pageBuilder: (context, state) => _buildPageWithAnimation(
          context,
          state,
          const TimeCapsuleSentPage(),
        ),
      ),

      // 时间胶囊详情页面
      GoRoute(
        path: '${AppRoutes.timeCapsuleDetail}/:id',
        name: 'time_capsule_detail',
        pageBuilder: (context, state) {
          final timeCapsuleId = state.pathParameters['id']!;
          return _buildPageWithAnimation(
            context,
            state,
            TimeCapsuleDetailPage(timeCapsuleId: timeCapsuleId),
          );
        },
      ),

      // 用户信息页面
      GoRoute(
        path: '${AppRoutes.userInfo}/:id',
        name: 'user_info',
        pageBuilder: (context, state) {
          final userId = state.pathParameters['id'];
          if (userId == null || userId.isEmpty) {
            // 如果没有传递用户ID，跳转到错误页面
            return _buildPageWithAnimation(
              context,
              state,
              Scaffold(
                appBar: AppBar(title: const Text('参数错误')),
                body: const Center(child: Text('缺少用户ID参数')),
              ),
            );
          }
          return _buildPageWithAnimation(
            context,
            state,
            UserInfoPage(userId: userId),
          );
        },
      ),

      // 消息列表页面
      GoRoute(
        path: AppRoutes.messageList,
        name: 'message_list',
        pageBuilder: (context, state) =>
            _buildPageWithAnimation(context, state, const MessageListPage()),
      ),

      // 聊天页面
      GoRoute(
        path: '${AppRoutes.chat}/:id',
        name: 'chat',
        pageBuilder: (context, state) {
          final userId = state.pathParameters['id']!;
          return _buildPageWithAnimation(
            context,
            state,
            ChatPage(userId: userId),
          );
        },
      ),

      // 订阅页面
      GoRoute(
        path: AppRoutes.subscribe,
        name: 'subscribe',
        pageBuilder: (context, state) => _buildPageWithAnimation(
          context,
          state,
          const SubscribePage(),
        ),
      ),
    ],

    // 错误页面处理
    errorBuilder: (context, state) => Scaffold(
      appBar: AppBar(title: const Text('page not found')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, size: 64, color: Colors.red),
            const SizedBox(height: 16),
            Text(
              'page not found: ${state.uri}',
              style: const TextStyle(fontSize: 18),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () => context.go(AppRoutes.login),
              child: const Text('back to login'),
            ),
          ],
        ),
      ),
    ),
  );

  static GoRouter get router => _router;

  /// 构建带动画的页面
  static Page<dynamic> _buildPageWithAnimation(
    BuildContext context,
    GoRouterState state,
    Widget child,
  ) {
    return CustomTransitionPage<void>(
      key: state.pageKey,
      child: child,
      transitionsBuilder: (context, animation, secondaryAnimation, child) {
        // 滑动动画
        const begin = Offset(1.0, 0.0);
        const end = Offset.zero;
        const curve = Curves.easeInOut;

        var tween = Tween(
          begin: begin,
          end: end,
        ).chain(CurveTween(curve: curve));

        return SlideTransition(position: animation.drive(tween), child: child);
      },
      transitionDuration: const Duration(milliseconds: 300),
      reverseTransitionDuration: const Duration(milliseconds: 300),
    );
  }

  /// 构建带条件动画的页面（根据来源页面选择动画）
  static Page<dynamic> _buildPageWithConditionalAnimation(
    BuildContext context,
    GoRouterState state,
    Widget child,
  ) {
    // 检查是否从native页面跳转过来
    final extra = state.extra as Map<String, dynamic>?;
    final fromNative = extra?['fromNative'] == true;

    return CustomTransitionPage<void>(
      key: state.pageKey,
      child: child,
      transitionsBuilder: (context, animation, secondaryAnimation, child) {
        if (fromNative) {
          // 从native页面来的使用渐变动画
          const curve = Curves.easeInOut;
          var fadeAnimation = Tween(
            begin: 0.0,
            end: 1.0,
          ).animate(CurvedAnimation(parent: animation, curve: curve));
          return FadeTransition(opacity: fadeAnimation, child: child);
        } else {
          // 其他页面来的使用滑动动画
          const begin = Offset(1.0, 0.0);
          const end = Offset.zero;
          const curve = Curves.easeInOut;
          var tween = Tween(
            begin: begin,
            end: end,
          ).chain(CurveTween(curve: curve));
          return SlideTransition(
            position: animation.drive(tween),
            child: child,
          );
        }
      },
      transitionDuration: Duration(milliseconds: fromNative ? 500 : 300),
      reverseTransitionDuration: Duration(milliseconds: fromNative ? 500 : 300),
    );
  }
}
